import 'package:flutter/material.dart';

import 'base_viewmodel.dart';

///提供viewModel绑定 model view的widget

class ViewModelBinder<T extends BaseViewModel> extends StatefulWidget {
  final T viewModel;
  final Widget child;

  ViewModelBinder({
    @required this.viewModel,
    @required this.child,
  });

  static T of<T extends BaseViewModel>(BuildContext context) {
    // final type = _typeOf<ViewModelBinder<T>>();
    // ancestorWidgetOfExactType 1.12.1已经废弃
    // ViewModelBinder<T> binder = context.ancestorWidgetOfExactType(type);
    ViewModelBinder<T> binder = context.findAncestorWidgetOfExactType();
    return binder.viewModel;
  }

  // static Type _typeOf<T>() => T;

  @override
  _ViewModelBinderState createState() => _ViewModelBinderState();
}

class _ViewModelBinderState extends State<ViewModelBinder> {
  @override
  Widget build(BuildContext context) {
    return widget.child;
  }

  @override
  void dispose() {
    widget.viewModel.dispose();
    super.dispose();
  }
}